package v1

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"jwgin/model/mysql"
	"jwgin/service"
	"jwgin/utils/datetime"
	ding "jwgin/utils/dingding"
	"strconv"
	"time"
)

type activitySign struct {
}

func (s *activitySign) Routers(Router *gin.RouterGroup) (R gin.IRoutes) {
	Router.GET("/activity/sign", s.getSign)
	Router.GET("/activity/sign/:id", s.get)
	Router.PUT("/activity/sign/:id", s.put)
	Router.GET("/activity/sign/:id/history", s.history)
	return Router
}

//获取签到活动
func (activitySign) getSign(c *gin.Context) {
	count, size, offset := pages(c)
	comid := c.GetUint("RoleID")
	if comid == 0 {
		RespErr(c, fmt.Errorf("系统用户认证失败"))
		return
	}
	db := service.G.Model(mysql.Activity{}).
		Where("comid = ?", comid).
		Where("activity_template_id = 1")
	list := []map[string]interface{}{}
	db.Count(&count).
		Offset(offset).
		Limit(size).
		Order("id DESC").
		Scan(&list)
	RespList(c, count, list)
}

//获取活动信息
func (activitySign) get(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		RespErr(c, fmt.Errorf("参数错误"))
		return
	}

	requ := make(map[string]interface{})
	service.G.Model(mysql.Activity{}).Where("id = ?", id).
		Joins("LEFT JOIN `activity_sign_rule` ON activity_sign_rule.sid = activity.id").
		Select("rule_bean,activity.*").Scan(&requ)
	RespSucc(c, requ)
}

//签到历史
func (activitySign) history(c *gin.Context) {
	count, size, offset := pages(c)
	comid := c.GetUint("RoleID")
	if comid == 0 {
		RespErr(c, fmt.Errorf("系统用户认证失败"))
		return
	}
	db := service.G.Model(mysql.ActivitySignRecord{}).
		Joins("JOIN `activity`  ON activity.id = activity_sign_record.activity_id").
		Where("comid = ?", comid)
	list := []map[string]interface{}{}
	db.Select("activity_name,activity_sign_record.*").Count(&count).
		Offset(offset).
		Limit(size).
		Order("id DESC").
		Scan(&list)
	RespList(c, count, list)
}

//签到
func (activitySign) put(c *gin.Context) {
	//活动正常否 1活动在不在 状态对不对 ,时间对不对
	//当天 签到了没有
	//签到
	//用户加积分
	//记流水

	id := c.Param("id")
	if id == "" {
		RespErr(c, fmt.Errorf("参数错误"))
		return
	}

	act := &mysql.Activity{}
	if err := service.G.Where("id = ?", id).First(act).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			RespErr(c, fmt.Errorf("请求失败"))
			return
		} else {
			RespErr(c, fmt.Errorf("非法操作,没有这个活动"))
			return
		}
	}

	if act.ActivityStatu != 1 {
		RespErr(c, fmt.Errorf("该活动不在进行中..."))
		return
	}
	fmt.Println("-------------------")
	fmt.Println(datetime.DateToint64(act.ActivityStart))
	fmt.Println(time.Now().Unix())
	fmt.Println(datetime.DateToint64(act.ActivityEnd))
	fmt.Println("-------------------")
	if datetime.DateToint64(act.ActivityStart) > time.Now().Unix() || datetime.DateToint64(act.ActivityEnd) < time.Now().Unix() {
		RespErr(c, fmt.Errorf("该活动不在进行中..."))
		return
	}

	userid := c.GetUint("UserID")
	if userid == 0 {
		RespErr(c, fmt.Errorf("系统用户认证失败"))
		return
	}

	t1, t2 := datetime.GetTime()
	Record := &mysql.ActivitySignRecord{}
	err := service.G.Where("uid = ?", userid).
		Where("addtime > ? AND addtime < ?", t1, t2).
		First(Record).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		RespErr(c, fmt.Errorf("请求失败"))
		return
	}

	if err != gorm.ErrRecordNotFound {
		RespErr(c, fmt.Errorf("当日已签到"))
		return
	}

	//查签到积分奖励
	rule := &mysql.ActivitySignRule{}
	if err = service.G.Where("sid = ?", act.Id).First(rule).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			RespErr(c, fmt.Errorf("请求失败"))
			return
		} else {
			RespErr(c, fmt.Errorf("当前活动奖励未配置,请联系管理员配置"))
			return
		}
	}

	user := &mysql.User{}
	service.G.Where("id = ?", userid).First(user)

	//签到
	//用户加积分
	//记流水
	tx := service.G.Begin()
	signins := &mysql.ActivitySignRecord{
		ActivityId: act.Id,
		Uid:        int(userid),
		Bean:       rule.RuleBean,
	}
	if err := tx.Create(signins).Error; err != nil {
		tx.Rollback()
		ding.DingErr(err.Error())
		RespErr(c, errors.New("fail"))
		return
	}
	if err := tx.Table("user").Where("id = ? ", userid).UpdateColumn("bean", gorm.Expr("bean + ?", rule.RuleBean)).Error; err != nil {
		tx.Rollback()
		ding.DingErr(err.Error())
		RespErr(c, errors.New("fail"))
		return
	}
	record := &mysql.RecordBean{
		Uid:       int(userid),
		Bean:      rule.RuleBean,
		BeforBean: user.Bean,
		AfterBean: user.Bean + rule.RuleBean,
		Type:      1,
		Info:      "签到",
		Orderid:   strconv.Itoa(signins.Id),
	}
	if err := tx.Create(record).Error; err != nil {
		tx.Rollback()
		ding.DingErr(err.Error())
		RespErr(c, errors.New("fail"))
		return
	}
	tx.Commit()
	RespSucc(c, nil)

}
